package com.itzg.vboxfarm.service;

import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Service;

import com.itzg.vboxfarm.domain.ConnectionStatus;
import com.itzg.vboxfarm.domain.HostMachine;
import com.itzg.vboxfarm.service.bits.HostChangedEvent;

@Service
public class HostStatsCollectionService implements ApplicationListener<HostChangedEvent>, SmartLifecycle {
	public static final int PHASE = Integer.MAX_VALUE;

	private static Logger logger = LoggerFactory.getLogger(HostStatsCollectionService.class);
	
//	private Map<HostMachine, HostStatsCollector> collectors = new HashMap<HostMachine, HostStatsCollector>();
	
	@Autowired
	HostConfigService hostConfigService;
	
	@Autowired
	HostStatsCollector hostStatsCollector;

	private boolean running;
	
	@Override
	public void onApplicationEvent(HostChangedEvent evt) {
		switch (evt.getType()) {
		case CONNECTED:
			logger.debug("Received event {}", evt);
			handleHostReady(evt.getHostMachine());
			break;
			
//		case REMOVED:
//			HostStatsCollector oldCollector = collectors.remove(evt.getHostMachine());
//			if (oldCollector != null) {
//				logger.debug("Stopping prior collection on {}", evt.getHostMachine());
//				oldCollector.stop();
//				oldCollector = null;
//			}
//			break;
		}
	}

	private void handleHostReady(HostMachine host) {
		hostStatsCollector.prepare(host);
	}

	@Override
	public boolean isRunning() {
		logger.debug("Somebody wants to know if I'm running, it's {}", running);
		return running;
	}

	@Override
	public void start() {
		logger.debug("Checking for existing hosts to start collecting");
		Collection<HostMachine> hosts = hostConfigService.getAllHosts();
		for (HostMachine hostMachine : hosts) {
			if (hostMachine.getConnectionStatus() == ConnectionStatus.VALID) {
				handleHostReady(hostMachine);
			}
		}
		running = true;
	}

	@Override
	public void stop() {
		logger.debug("Stopping synchronous");
	}

	@Override
	public int getPhase() {
		return PHASE;
	}

	@Override
	public boolean isAutoStartup() {
		return true;
	}

	@Override
	public void stop(Runnable callback) {
//		logger.debug("Stopping async");
//		Collection<HostStatsCollector> values = collectors.values();
//		for (HostStatsCollector hostStatsCollector : values) {
//			hostStatsCollector.stop();
//		}
		running = false;
		callback.run();
	}
}
